﻿using Microsoft.Xna.Framework;
using SolarWinds.Helpers;
using SolarWinds.Input;
using SolarWinds.Nodes;
using SolarWinds.Logic;
using SolarWinds.Scene;

namespace SolarWinds.Controllers
{
    class GameShipController : GameComponent
    {
        public SceneNode Ship { get; set; }
        private ISceneManagerService mScene;

        public GameShipController(Game game) : base(game)
        {
        }

        public override void Initialize()
        {
            base.Initialize();

            var input = (IInputManagerService)Game.Services.GetService(typeof(IInputManagerService));

            input.Mouse.ButtonPressed += MouseButtonPressed;
            input.Mouse.ButtonReleased += MouseButtonReleased;
            input.Mouse.Moved += MouseMoved;

            mScene = (ISceneManagerService)Game.Services.GetService(typeof(ISceneManagerService));
        }

        private const float MouseSpeed = 4.0f;

        void MouseMoved(object sender, MouseEvent e)
        {
            Vector3 shipPosition = Ship.Position;

            shipPosition += new Vector3(-e.RelativePosition.X *MouseSpeed, -e.RelativePosition.Y * MouseSpeed, 0.0f);

            Ship.Position = shipPosition;
        }

        private bool mShipFire;

        void MouseButtonReleased(object sender, MouseEvent e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mShipFire = false;
            }

        }

        void MouseButtonPressed(object sender, MouseEvent e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mShipFire = true;
            }
        }

        float projectileFireRate; // TODO move to ProjecttileData class
        private float projectileFireSpeed = 3; // TODO move to ProjecttileData class

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (mShipFire)
            {
                projectileFireRate -= (float) gameTime.ElapsedGameTime.TotalMilliseconds;
                if (projectileFireRate < 0.0f)
                {
                    var projectile = new Projectile(Game)
                                         {
                                             Direction = Vector3.UnitY * projectileFireSpeed,
                                             Position = Ship.Position,
                                             Rotation = Quaternion.CreateFromAxisAngle(Vector3.UnitX, 90),
                                             Scale = new Vector3(1.0f, 1.0f, 1.0f)
                                         };
                    mScene.AddNode(projectile);

                    projectileFireRate = 150.0f;
                }
            }
        }
    }
}
